/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* ret;
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        ret = nullptr;
        _helper(root, p, q);
        return ret;
    }

    int _helper(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        if (root == nullptr || ret != nullptr) return 0;

        int tmp = 0;
        if (root == p)tmp = 1;
        else if (root == q)tmp = 2;

        tmp += _helper(root->left, p, q) + _helper(root->right, p, q);

        if (tmp == 3 && ret == nullptr) ret = root;
        return tmp;
    }


};